use std::{rc::Rc, cell::RefCell, fs::File, io::Read};

// use mlua::{Lua, AnyUserData, UserData};

use lua::core::LuaEngine;

use crate::vulkan::object::object::{Componentable, Object, ComponentableContext};

use super::{component::BaseComponent, transform_component::TransfromComponent};
// use super::component::ObjectComponent;

#[derive(Clone)]
pub struct LuaComponent {
    base_component: BaseComponent,
    // special data
    lua_script: String
}

impl Default for LuaComponent {
    fn default() -> Self {
        Self {
            lua_script: String::new(),

            base_component: BaseComponent::default()
        }
    }
}

impl Componentable for LuaComponent {
    fn tick(&mut self, delta_time: f32, context: &ComponentableContext) {
        self.run_script(context);
    }

    fn post_load(&mut self, parent_object: Rc<RefCell<dyn Object>>, context: &mut ComponentableContext) {
        self.base_component.post_load(parent_object, context);

        // Load Lua File
        let mut lua_file = File::open("./vulkan-tutorial-rs/assets/lua_test.lua").expect("[Error] Failed to Load lua file");
        lua_file.read_to_string(&mut self.lua_script).expect("failed");
    }
}

impl LuaComponent {
    pub fn run_script(&self, context: &ComponentableContext) {
        context.lua_engine.run_script(&self.lua_script);
    }
}